﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace PrjUIExDemo
{
    public class TreeViewModel : BindableBase
    {
        protected bool _isChecked;
        public bool IsChecked
        {
            get => _isChecked; set
            {
                SetProperty(ref _isChecked, value);
                SetIsChecked(value, true, true);
            }
        }

        protected string _name;
        public string Name { get => _name; set => SetProperty(ref _name, value); }

        protected Visibility _visibility;
        public Visibility Visibility { get => _visibility; set => SetProperty(ref _visibility, value); }

        protected TreeViewModel _parent = null;
        public TreeViewModel Parent { get => _parent; set => SetProperty(ref _parent, value); }

        public ICollection<TreeViewModel> Children { get; set; } = new List<TreeViewModel>();


        private void SetIsChecked(bool value, bool updateChildren, bool updateParent)
        {
            if (updateChildren)
            {
                Children.ToList().ForEach(c => c.SetIsChecked(value, true, false));
            }
            if (updateParent && _parent != null)
            {
                _parent.VerifyCheckState();
            }
        }

        private void VerifyCheckState()
        {
            int count = Children.Where(x => x.IsChecked == false).Count();
            bool state = count > 0 ? false : true;
            IsChecked = state;
            SetIsChecked(state, false, true);
        }

    }
}
